<?php

namespace App\WeChat\Message;

use App\Model\MpInActivitySubscribeUserModel;
use App\Model\MpInviteCodeModel;
use App\Model\MpInvitedModel;
use App\Model\MpQrDefModel;
use App\Model\UserModel;
use App\WeChat\Message\Activity\Activity;
use App\WeChat\Message\Activity\InviteMessage;
use App\WeChat\WeChatUtil;
use EasySwoole\WeChat\Bean\OfficialAccount\RequestMsg;

class OnMessageUnsubscribe
{
    public static function handle(RequestMsg $msg)
    {
        $userModel = new UserModel();
        $userModel->setSubscribeStatus($msg->getFromUserName(), false);
        self::addUnsubscribeFlag($msg);
        self::handleBUnsubscribe($msg);
        return null;
    }

    private static function addUnsubscribeFlag(RequestMsg $msg)
    {
        sgo(function () use ($msg) {
            $nickname = (new MpInActivitySubscribeUserModel())->getNickname($msg->getFromUserName());
            (new MpInActivitySubscribeUserModel())->add($msg->getFromUserName(), MpInActivitySubscribeUserModel::flagUnSubscribe, $nickname);
        });
    }

    //活动期间B取消关注
    private static function handleBUnsubscribe(RequestMsg $msg)
    {
        if (Activity::isActivity()) {
            self::handleBUnsubscribeByOpenid($msg->getFromUserName());
        }
    }

    static function handleBUnsubscribeByOpenid(string $openid)
    {
        sgo(function () use ($openid) {
            $code = (int)((new MpInvitedModel())->findByOpenid($openid, ['code'])['code'] ?? 0);
            if ($code) {
                $nickname = (new MpInActivitySubscribeUserModel())->getNickname($openid);
                self::decrInvitedByCode($code, $nickname, $openid);
            }
        });
    }

    //好友取消关注
    static function decrInvitedByCode(int $code, string $nickname, string $openid)
    {
        $currCount = (new MpInviteCodeModel())->decrInvitedCountByCode($code);
        //code 数据
        $codeModel = (new MpInviteCodeModel());
        $codeData  = $codeModel->findByCode($code, ['qid', 'is_complete']);
        if (!$codeData) {
            return;
        }
        //如果已经完成则锁定不进行减操作
        if ($codeData['is_complete'] == 1) {
            return;
        }
        $def      = (new MpQrDefModel())->findById($codeData['qid']);
        $need     = $def['need'];
        $giftName = $def['name'];
        //通知A好友取消了关注
        $openidOfA = (new MpInviteCodeModel())->findByCode($code, ['openid'])['openid'] ?? '';
        if (!empty($openidOfA)) {
            $util = new WeChatUtil();
            $msg  = InviteMessage::onBUnSubscribeAndInActivityMessage($nickname, $need, $currCount, $giftName);
            $util->sendTextMsg($openidOfA, $msg, $util->getAccessToken());
        }
    }
}